//
//  APIRequest.swift
//  FG
//
//  Created by 红沙尘 on 2018/11/4.
//  Copyright © 2018年 红沙尘. All rights reserved.
//

import UIKit
import Alamofire

let api_host = "http://xxx.xxx.xxx.xxx"


class APIRequest: NSObject {

    
    /// 以raw方式请求后台
    ///
    /// - Parameters:
    ///   - url: 请求地址
    ///   - parameter: 请求参数
    ///   - success: 成功回调
    ///   - error: 失败回调
    class func post(url:String,
                    parameter:NSDictionary,
                    success:@escaping(_ response:NSDictionary) -> (),
                    error:@escaping(_ error:Error) -> ()) {
        let urlString = api_host + url
        let json = String(stringByDictionary(dictionary: parameter))
        let url  = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        
        var request = URLRequest(url: url)
        
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        request.httpBody = jsonData
        
        Alamofire.request(request).responseJSON {
            (response) in
            
            if response.result.error == nil {
                if response.result.isSuccess == true {
                    if let jsons = response.result.value {
                        success(jsons as! NSDictionary)
                    } else {
                        print("❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌")
                        print("数据异常:"+urlString)
                        print(response.result)
                    }
                } else {
                    print("❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌")
                    print("数据异常:"+urlString)
                    print(response.result)
                }
            } else {
                print("❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌")
                print("数据异常:"+urlString)
                print(response)
                print(response.result.error ?? "")
                error(response.result.error!)
            }
        }
    }
    
    
    /// 字典转成字符串
    ///
    /// - Parameter dictionary: 字典参数
    /// - Returns:  String结果
    class func stringByDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try! JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return String(JSONString!)
    }
    
    //MARK: - 文件上传
    
    class func uploadFile(successBack:@escaping(_ response:[String: Any]) -> (),
                          error:@escaping(_ error:Error) -> ()) {
        print("开始上传")
        let image = UIImage(named: "BGTest")
        let imageData = UIImagePNGRepresentation(image!)!
        let url = URL(string: "http:xxx.xxx.xxx.xxx" + "/coach/v1/files/upload")!
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        let token = "xxxxxxxxxx"
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            let fileName = String(format: "%d.png", Date().timeIntervalSinceNow)
            multipartFormData.append(imageData,
                                     withName: "files[]",
                                     fileName: fileName,
                                     mimeType: "image/png")
        }, with: request) { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if let value = response.result.value as? [String: AnyObject] {
                        successBack(value)
                        print(value)
                    }
                }
                break
            case .failure( _):
                break
            }
        }
    }
    
}
